<?php

namespace app\components;

class Pass {

	public static $key='feeyocardpass';

	/**
	 * 加密函数
	 * [encrypt description]
	 * @param  [type] $txt [description]
	 * @return [type]      [description]
	 */
	public static function encrypt($txt)
	{
		$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		$nh = rand(0,64);
		$ch = $chars[$nh];
		$mdKey = md5(self::$key.$ch);
		$mdKey = substr($mdKey,$nh%6, $nh%6+31);
		$txt = base64_encode($txt);
		$tmp = '';
		$i=0;$j=0;$k = 0;
		for ($i=0; $i<strlen($txt); $i++) {
		  $k = $k == strlen($mdKey) ? 0 : $k;
		  $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%64;
		  $tmp .= $chars[$j];
		}
		return $ch.$tmp;
	}

	/**
	 * 解密函数
	 * [decrypt description]
	 * @param  [type] $txt [description]
	 * @return [type]      [description]
	 */
	public static function decrypt($txt)
	{
		$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		$ch = $txt[0];
		$nh = strpos($chars,$ch);
		$mdKey = md5(self::$key.$ch);
		$mdKey = substr($mdKey,$nh%6, $nh%6+31);
		$txt = substr($txt,1);
		$tmp = '';
		$i=0;$j=0; $k = 0;
		for ($i=0; $i<strlen($txt); $i++) {
		  $k = $k == strlen($mdKey) ? 0 : $k;
		  $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
		  while ($j<0) $j+=64;
		  $tmp .= $chars[$j];
		}
		return base64_decode($tmp);
	}
    
    /**
     * 解密函数 去空字符
     * [decrypt_trim description]
     * @param  [type] $txt [description]
     * @return [type]      [description]
     */
    public static function decrypt_trim ($txt)
    {
        return trim(self::decrypt($txt));
    }

    /**
     * Returns an encrypted & utf8-encoded
     * [encrypt_with_key description]
     * @param  [type] $pure_string    [description]
     * @param  [type] $encryption_key [description]
     * @return [type]                 [description]
     */
    public static function encrypt_with_key ($pure_string, $encryption_key)
    {
        $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv);
        return $encrypted_string;
    }

    /**
     * Returns decrypted original string
     * [decrypt_with_key description]
     * @param  [type] $encrypted_string [description]
     * @param  [type] $encryption_key   [description]
     * @return [type]                   [description]
     */
    public static function decrypt_with_key($encrypted_string, $encryption_key)
    {
        $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv);
        return $decrypted_string;
    }
}